package com.tb.education.common.packets;

import cn.hutool.core.date.DateUtil;
import org.tio.core.intf.Packet;

import java.io.UnsupportedEncodingException;

/**
 * @author wangze
 * @date 2020-07-10 20:51.
 **/
public class DevicePacket extends Packet {
	//消息头的长度
	public static final int HEADER_LENGHT = 4;
	public static final String CHARSET = "utf-8";
	private byte[] body;
	private String operationType;

	/**
	 * @return the body
	 */
	public byte[] getBody() {
		return body;
	}

	/**
	 * @param body the body to set
	 */
	public void setBody(byte[] body) {
		this.body = body;
	}

	public static int getHeaderLenght() {
		return HEADER_LENGHT;
	}

	public static String getCHARSET() {
		return CHARSET;
	}

	public String getOperationType() {
		return operationType;
	}

	public void setOperationType(String operationType) {
		this.operationType = operationType;
	}


	/**
	 * 解析byte
	 *
	 * @param body
	 */
	public static MsgWrapper parseByte(byte[] body) throws UnsupportedEncodingException {
		String str = new String(body, DevicePacket.getCHARSET());
		if (!str.startsWith(Msg.PREFIX)) {
			return null;
		}
		if (!str.endsWith(Msg.SUFFIX)) {
			return null;
		}

		str = str.substring(1, str.length() - 1);
		String[] values = str.split(Head.SEPARATOR);
		if (values.length != 8) {
			return null;
		}
		Head head = new Head();
		head.setDeviceNo(values[0]);
		head.setIccId(values[1]);
		head.setSerialNo(values[2]);
		head.setOperationType(values[3]);
		head.setPacketType(Integer.valueOf(values[4]));
		head.setTime(DateUtil.parseLocalDateTime(values[5], "yyyyMMddHHmmss"));
		head.setPacketLength(Integer.valueOf(values[6]));
		if (values[7].length() != head.getPacketLength()) {
			return null;
		}
		MsgWrapper msgWrapper = new MsgWrapper();
		msgWrapper.setHead(head);
		msgWrapper.setBody(values[7]);
		return msgWrapper;
	}

}
